package com.example.lib_base.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get

/**
 * Created by luyao
 * on 2019/5/31 15:44
 */
abstract class BaseActivity : AppCompatActivity() {
    //自己viewModel
    private var mActivityProvider: ViewModelProvider? = null

    //全局viewModel
    private var mApplicationProvider: ViewModelProvider? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutResId())
        initViewModel()
        initViewOrObserve()
    }

    abstract fun getLayoutResId(): Int
    protected abstract fun initViewOrObserve()
    protected abstract fun initViewModel()

    protected open fun <T : ViewModel> getActivityScopeViewModel(modelClass: Class<T>): T {
        if (mActivityProvider == null) {
            mActivityProvider = ViewModelProvider(this)
        }
        return mActivityProvider!![modelClass]
    }

    protected open fun <T : ViewModel> getApplicationScopeViewModel(modelClass: Class<T>): T {
        if (mApplicationProvider == null) {
            mApplicationProvider = ViewModelProvider((this.applicationContext as BaseApplication))
        }
        return mApplicationProvider!![modelClass]
    }

}